package com.interviewbackend.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class InformationPreprocessingClient {

    @Value("${qwen.api.key}")
    private String apiKey;

    @Value("${qwen.api.url}")
    private String apiUrl;

    @Value("${qwen.model.name}")
    private String modelName;

    private OpenAIClient client;

    @PostConstruct
    public void init() {
        client = OpenAIOkHttpClient.builder()
                .apiKey(apiKey)
                .baseUrl(apiUrl)
                .build();
    }

    public String chat(String prompt) {
        try {
            ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                    .model(modelName)
                    .addUserMessage(prompt)
                    .build();

            ObjectMapper mapper = new ObjectMapper();
            System.out.println("🔥 调用模型：" + modelName);
            System.out.println("🔥 请求参数：" + mapper.writeValueAsString(params));

            Object raw = client.chat().completions().create(params); // 报错就在这里
            System.out.println("✅ 调用成功，返回类型：" + raw.getClass());

            Map<String, Object> resultMap = mapper.convertValue(raw, Map.class);
            List<Map<String, Object>> choices = (List<Map<String, Object>>) resultMap.get("choices");
            if (choices != null && !choices.isEmpty()) {
                Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                if (message != null && message.get("content") != null) {
                    return message.get("content").toString().trim();
                }
            }

            return "【AI生成失败：未提取到内容】";
        } catch (Exception e) {
            System.err.println("❌ 调用大模型失败，异常类型：" + e.getClass().getName());
            System.err.println("❌ 异常信息：" + e.getMessage());
            e.printStackTrace();
            return "【AI生成失败，请稍后再试】";
        }
    }

    public String extractKeywords(String resumeText) {
        String prompt = "请从以下简历内容中提取**最能体现候选人技能与经历**的5个关键词，" +
                "关键词尽量用中文，除非一些是英文专有名词，用英文逗号分隔，**只返回关键词，不要添加任何说明或标点符号**。\n\n" +
                "简历内容如下：\n" + resumeText;
        return chat(prompt);
    }

    public String detectJobType(String resumeText) {
        String prompt = """
            请根据以下简历内容判断候选人最可能申请的岗位，三选一，仅返回岗位英文名，禁止任何额外说明或换行。

            可选岗位如下：
            - big_data
            - ai
            - iot

            简历内容如下：
            """ + resumeText;
        return chat(prompt);
    }



}
